from rest_framework import serializers
from .models import Environment, TestCase, TestExecution, TestReport, DailyLog


class EnvironmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Environment
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')




class TestCaseSerializer(serializers.ModelSerializer):
    environment_name = serializers.CharField(source='environment.name', read_only=True)
    created_by_username = serializers.CharField(source='created_by.username', read_only=True)
    def to_internal_value(self,data):
        return super().to_internal_value(data)

    def to_representation(self, instance):
        ret =  super().to_representation(instance)
        return ret
    class Meta:
        model = TestCase
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')


class TestExecutionSerializer(serializers.ModelSerializer):
    test_case_name = serializers.CharField(source='test_case.name', read_only=True)
    environment_name = serializers.CharField(source='environment.name', read_only=True)
    created_by_username = serializers.CharField(source='created_by.username', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = TestExecution
        fields = '__all__'
        read_only_fields = ('created_at',)


class TestReportSerializer(serializers.ModelSerializer):
    created_by_username = serializers.CharField(source='created_by.username', read_only=True)

    class Meta:
        model = TestReport
        fields = '__all__'
        read_only_fields = ('created_at',)


class TestCaseDetailSerializer(TestCaseSerializer):
    """测试用例详情序列化器，包含执行历史"""
    executions = TestExecutionSerializer(many=True, read_only=True)

    class Meta(TestCaseSerializer.Meta):
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')


class DailyLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = DailyLog
        fields = '__all__' 